/*
 * EvolutionFrame.java
 *
 * Created on den 29 oktober 2007, 22:53
 */
package grex.Graphics;

import grex.WekaModels.GrexM5P;
import grex.Environment;
import grex.ErrorManagement.ErrorManager;
import grex.ErrorManagement.EvolutionListener;
import grex.EvolutionProcess;
import grex.IO.FileOutputHandler;
import grex.GP;
import grex.IO.GoogleMailer;
import grex.Options;
import grex.SimplificationListener;
import grex.Simplyfier;
import grex.TreeComparator;
import grex.fitnessfunctions.Classification.MultipleSolutionsFitness;
import grex.fitnessfunctions.ErrorFunctions.ErrorCalculator;
import grex.Nodes.GeneException;
import java.awt.*;
import java.beans.PropertyVetoException;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.MessagingException;
import javax.swing.*;
import javax.swing.plaf.DesktopPaneUI;

/**
 *
 * @author  RIK
 */
public class EvolutionFrame extends javax.swing.JInternalFrame implements EvolutionListener, SimplificationListener {

    /** Creates new form EvolutionFrame */
    EvolutionProcess ep;
    Options options;
    TreePanel lastPanel, lastSimpPanel;
    ArrayList<TreePanel> treePanels;
    int numberOfRuns = 0;
    TreeComparator tc = new TreeComparator();
    private static int frameCount =0;
    
    private boolean closeWhenReady = false;
    public EvolutionFrame(EvolutionProcess ep, Options options, boolean closeWhenReady) {
        initComponents();
       // jTabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        jTabbedPane.setTabPlacement(jTabbedPane.LEFT);
        this.closeWhenReady = closeWhenReady;

        jpgbGeneration.setForeground(Color.blue);
        if(!options.getFITNESS_FUNCTION().equalsIgnoreCase("MultipleSolutionsFitness"))
            jbtnShowSolutions.setVisible(false);
        jbtnAlternativeS.setVisible(false);
        jbtnShowPrediction.setVisible(options.getPROBLEM_TYPE()==Options.REGRESSION);
        this.options = options;
        this.ep = ep;
        ep.addEvolutionListener(this);
        ep.addSimplificationListener(this);
       // ep.addEvolutionListener(tc);
        jtxaOptions.setText(options.toString());
       // if (false && options.getPROBLEM_TYPE() != Options.REGRESSION) {
            jbtnShowPrediction.setVisible(true);
      // }
        this.setTitle(options.getDATA_FILE());
        this.maximizable=true;
        this.resizable=true;
        this.isMaximum=true;
        //repaint();
        validate();
        //this.toFront();
        //this.setLocation(30*frameCount, 30*frameCount);

        Component[] cs = jpnlButtons.getComponents();
        for(int i = 0;i<cs.length;i++)
            if(cs[i] instanceof JButton)
                cs[i].setVisible(false);
        frameCount++;
    }

    private void addNewEvolutionTab(String title) {

        if (lastPanel != null) {
            ep.removeEvolutionLister(lastPanel);
        }
        JPanel p = new JPanel();
        p.setLayout(new GridLayout(2,1));
        lastPanel = new TreePanel(null, "",ep.getEnvironment().getErrorCalculator());        
        ep.addEvolutionListener(lastPanel);        
        p.add(lastPanel);
        
        JPanel jpnlStats = new JPanel();
        jpnlStats.setLayout(new GridLayout(2,1));
        p.add(jpnlStats);
        
        GraphWindow gw;
        try {
            gw = new GraphWindow(ep,this);
            ep.addEvolutionListener(gw);
            jpnlStats.add(gw);
        } catch (GeneException ex) {
            Logger.getLogger(EvolutionFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        PerformancePanel pp = new PerformancePanel();
        ep.addEvolutionListener(pp);
        jpnlStats.add(pp);
        

        
        
        jTabbedPane.addTab(title, new CloseTabIcon(), p);
        jTabbedPane.setSelectedComponent(p);
        jTabbedPane.validate();

    }
     private void addNewPerformanceTab(String title) {
         
         try{
        PerformancePanel pp = new PerformancePanel();
        ep.addEvolutionListener(pp);
        jTabbedPane.addTab(title, new CloseTabIcon(), pp);
         }catch(Exception e){
             System.out.println("Error addaing Performance Tab");
             e.printStackTrace();
         }
    }

    private void addNewOptimizationTab(TreePanel panel) {

        GP gp = (GP) panel.getGP().clone();

        TreePanel p = new TreePanel(gp, "Optimized GP",ep.getEnvironment().getErrorCalculator());
        String titel = jTabbedPane.getTitleAt(jTabbedPane.indexOfComponent(panel));
        jTabbedPane.addTab("O(" + titel + ")", new CloseTabIcon(), p);
        jTabbedPane.setSelectedComponent(p);
        jTabbedPane.validate();
        p.update();


    }

    private void addBatchResultTab(EvolutionProcess ep) {
        try{
        JPanel jpnlResult = new JPanel();
        JScrollPane jScrollPaneResult = new JScrollPane();
        JTextArea jtxaResult = new JTextArea();
        jpnlResult.setLayout(new java.awt.BorderLayout());

        jScrollPaneResult.setAutoscrolls(true);
        jScrollPaneResult.setEnabled(false);

        jtxaResult.setColumns(20);
        jtxaResult.setEditable(false);
        jtxaResult.setRows(5);
        jtxaResult.setTabSize(4);
        jScrollPaneResult.setViewportView(jtxaResult);

        jpnlResult.add(jScrollPaneResult, java.awt.BorderLayout.CENTER);
      
        //jtxaResult.setText(ep.getLastBatchResult().toString());
        try {
            String s;      
            
              s = ep.getEnvironment().getErrorCalculator().getStatistics(ep.getBatchGPs());
              jtxaResult.setText(s +"\n" +ep.getBestGP().getFormatedTree());
              
              if (options.isAUTO_SAVE()) {
                saveResults(s+"\n" + options, ep);
                return;
              }              
              
        } catch (GeneException ex) {
            ErrorManager.getInstance().reportError(ex);
        }
        jTabbedPane.addTab("Results E" + numberOfRuns, new CloseTabIcon(), jpnlResult);
        jTabbedPane.setSelectedComponent(jpnlResult);
      //  jTabbedPane.validate();
        }
        catch(Exception e){
             System.out.println("Error addaing BatchResult Tab");
             e.printStackTrace();
         }
    }
    private void saveResults(String results, EvolutionProcess ep){
        if(options.isAUTO_SAVE()){
        FileOutputHandler f = new FileOutputHandler(options);
        String fileName = options.getDATA_FILE()+ "_" +  options.getFITNESS_FUNCTION() + "_" + System.currentTimeMillis()+".txt" ;
        f.openFile(fileName);
        f.printString(results);
         f.closeFile();
          if (options.getRECIPIENTS().length() != 0) {
            try {
                GoogleMailer.sendSSLMessage(options.getRECIPIENTS(), "Summary for " + this.getTitle() + options.getFITNESS_FUNCTION() + ".txt", results);
            } catch (MessagingException ex) {
                ErrorManager.getInstance().reportError(ex);
            }

        }
    }
    }
    
    private void addBatchSelectedResultTab(EvolutionProcess ep) {
        JPanel jpnlResult = new JPanel();
        JScrollPane jScrollPaneResult = new JScrollPane();
        JTextArea jtxaResult = new JTextArea();
        jpnlResult.setLayout(new java.awt.BorderLayout());

        jScrollPaneResult.setAutoscrolls(true);
        jScrollPaneResult.setEnabled(false);

        jtxaResult.setColumns(20);
        jtxaResult.setEditable(false);
        jtxaResult.setRows(5);
        jtxaResult.setTabSize(4);
        jScrollPaneResult.setViewportView(jtxaResult);

        jpnlResult.add(jScrollPaneResult, java.awt.BorderLayout.CENTER);
        jtxaResult.setText(ep.getSelectedResult(options.getTestFOLD()).toString());

        jTabbedPane.addTab("Res. Sel. E" + numberOfRuns, new CloseTabIcon(), jpnlResult);
        jTabbedPane.setSelectedComponent(jpnlResult);
        jTabbedPane.validate();
    }

    private JPanel addSummaryTab(EvolutionProcess ep) {
        try{
        JPanel jpnlResult = new JPanel();
        JScrollPane jScrollPaneResult = new JScrollPane();
        JTextArea jtxaResult = new JTextArea();
        jpnlResult.setLayout(new java.awt.BorderLayout());

        jScrollPaneResult.setAutoscrolls(true);
        jScrollPaneResult.setEnabled(false);

        jtxaResult.setColumns(20);
        jtxaResult.setEditable(false);
        jtxaResult.setRows(5);
        jtxaResult.setTabSize(4);
        jScrollPaneResult.setViewportView(jtxaResult);

        jpnlResult.add(jScrollPaneResult, java.awt.BorderLayout.CENTER);
        /*if (options.getPROBLEM_TYPE() == Options.CLASSIFICATION) {
            jtxaResult.setText(ep.getSummary());
        } else {
            // jtxaResult.setText(ep.getSummary());
            jtxaResult.setText(ep.getRegressionResults() + "\n" + options.toString());
        }*/
            jtxaResult.setText(ep.getSummary());
        jTabbedPane.addTab("Summary " + numberOfRuns, new CloseTabIcon(), jpnlResult);
        jTabbedPane.setSelectedComponent(jpnlResult);
        jTabbedPane.validate();
        return jpnlResult;
        }catch(Exception e){
             System.out.println("Error adding Summary Tab");
             e.printStackTrace();
             return null;
         }
        
        
    }

    private void showSimplificationTab() {
        String title = jTabbedPane.getTitleAt(jTabbedPane.getSelectedIndex());
        jTabbedPane.addTab("S(" + title + ")", new CloseTabIcon(), lastSimpPanel);
        jTabbedPane.setSelectedComponent(lastSimpPanel);
        jTabbedPane.validate();
    }

    private void initSimplificationTab() {
        if (lastSimpPanel != null) {
            ep.removeSimplificationListener(lastSimpPanel);
        }
        
        lastSimpPanel = new TreePanel(null, "",ep.getEnvironment().getErrorCalculator());
        lastSimpPanel.setModified(true);
        ep.addSimplificationListener(lastSimpPanel);
    }

    private void setRuningModeOnButtons() {
        jbtnSimplify.setEnabled(false);
        jbtnStart.setEnabled(false);
        jbtnStop.setEnabled(true);
        jbtnSave.setEnabled(false);
    }

    private void setStopModeOnButtons() {
        jbtnSimplify.setEnabled(true);
        jbtnStart.setEnabled(true);
        jbtnStop.setEnabled(false);
        jbtnSave.setEnabled(true);
    }

    private void updateCurrentTab() {
        
        int panel = jTabbedPane.getSelectedIndex();
        if (jTabbedPane.getSelectedComponent() instanceof TreePanel) {
            TreePanel jp = (TreePanel) jTabbedPane.getComponent(panel);//getTabComponentAt(panel);
            jp.update();
        }
        this.validate();//*/
    }

    private void saveSelectedGPTab() {
        GP gp = ((TreePanel) jTabbedPane.getSelectedComponent()).getGP();
        ((TreePanel) jTabbedPane.getSelectedComponent()).setModified(true);
        FileOutputHandler f = new FileOutputHandler(options);
        Component c = this.getParent();
        while (c.getParent() != null) {
            c = c.getParent();
        }
        FileDialog jf = new FileDialog((JFrame) c, "Save tab", FileDialog.SAVE);
        jf.setDirectory(options.getDATA_FILE());
        jf.setVisible(true);
        if (jf.getFile() != null) {
            try {
                f.openFile(jf.getDirectory() + jf.getFile());
                f.printString(options.toString());
                f.printString(gp.getStatisticsAsString());
                f.printString(gp.getFormatedTree());
                f.printString("\n----------Testset output---------------\n");
                f.printString(gp.getGPTestPrediction());
                f.closeFile();
            } catch (GeneException ex) {
                ErrorManager.getInstance().reportError(ex);
            }
        }
    }

    public void saveSelectedTextAreaTab() {
        //   ((TreePanel) jTabbedPane.getSelectedComponent()).setModified(true);
        JPanel p = (JPanel) jTabbedPane.getSelectedComponent();
        JScrollPane s = (JScrollPane) p.getComponent(0);
        JTextArea ta = (JTextArea) s.getViewport().getComponent(0);
        Component c = this.getParent();
        while (c.getParent() != null) {
            c = c.getParent();
        }
        FileDialog jf = new FileDialog((JFrame) c, "Save tab", FileDialog.SAVE);
        jf.setDirectory(options.getDATA_FILE());
        jf.setVisible(true);

        FileOutputHandler f = new FileOutputHandler(options);
        if (jf.getFile() != null) {
            f.openFile(jf.getDirectory() + jf.getFile());
            f.printString(ta.getText());
            f.closeFile();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    public void evolutionStarted(EvolutionProcess source) {

        jpgbProgress.setMaximum(options.getGENERATIONS() * options.getBATCH_SIZE());
        jpgbProgress.setValue(0);
        jpgbGeneration.setMaximum(options.getGENERATIONS());
        jpgbGeneration.setValue(0);
        if (options.isSIMPLIFICATION()) {
            initSimplificationTab();
        }
        numberOfRuns++;

        String title = options.getTestFOLD() + " E:" + numberOfRuns;
        if (options.getBATCH_SIZE() > 1) {
            title += " B:1";
        }
        addNewEvolutionTab(title);
       // if(options.getPROBLEM_TYPE()==Options.CLASSIFICATION)
      //      addNewPerformanceTab("P-" +title);
        setRuningModeOnButtons();
    }

    public void generationTerminated(EvolutionProcess source) {
        jpgbProgress.setValue(options.getGENERATIONS() * (source.getCurrentBatch() - 1) + source.getCurrentGeneration());
        jpgbGeneration.setValue(source.getCurrentGeneration());
    }

    public void batchTerminated(EvolutionProcess source) {
        if (source.getCurrentBatch() != options.getBATCH_SIZE()) {
            String title = options.getTestFOLD() + " E:" + numberOfRuns + " B:" + (source.getCurrentBatch() + 1);
            addNewEvolutionTab(title);
        //    if(options.getPROBLEM_TYPE()==Options.CLASSIFICATION)
         //       addNewPerformanceTab(options.getTestFOLD() + " P:" + numberOfRuns);
        }else{
                   addBatchResultTab(source); 
        }

    }

    public void evolutionTerminated(EvolutionProcess source) {
        setStopModeOnButtons();
        //  addBatchSelectedResultTab(source);
    }

    public void evolutionProcessTerminated(EvolutionProcess source) {
        //Todo: fixa summary f�r regression

        JPanel normSum = addSummaryTab(ep);

        JScrollPane s = (JScrollPane) normSum.getComponent(0);
        JTextArea ta = (JTextArea) s.getViewport().getComponent(0);
        
        if (options.isAUTO_SAVE()) {
            FileOutputHandler f = new FileOutputHandler();
            FileOutputHandler self = new FileOutputHandler();
            Calendar c = Calendar.getInstance();
            String d = "";
            d += c.get(Calendar.YEAR);
            d += c.get(Calendar.MONTH) + 1;
            d += c.get(Calendar.DAY_OF_MONTH);
            d += "-";
            d += c.get(Calendar.HOUR_OF_DAY);
            d += c.get(Calendar.MINUTE);
            d += c.get(Calendar.SECOND);
            if (!this.getTitle().contains(File.separator)) {
                f.openFile("." + File.separatorChar  + File.separator + "Summary for " + this.getTitle() + d + ".txt");
                //self.openFile("."+File.separatorChar+"Results"+File.separator+"Selected Summary for " + this.getTitle() + d + ".txt");
            } else {
                String[] sn = this.getTitle().split(File.separator);
                f.openFile("." + File.separatorChar  + File.separator + "Summary for " + sn[sn.length - 1] + d + ".txt");
                // self.openFile("."+File.separatorChar+"Results"+File.separator+"Selected"+sn[sn.length-1] + d + ".txt");
            }
            f.printString(ta.getText());
            // self.printString(selTa.getText());
            f.closeFile();
            // self.closeFile();
        }
        if (options.getRECIPIENTS().length() != 0) {
            try {
                GoogleMailer.sendSSLMessage(options.getRECIPIENTS(), "Summary for " + this.getTitle() + options.getFITNESS_FUNCTION() + ".txt", ta.getText());
            } catch (MessagingException ex) {
                ErrorManager.getInstance().reportError(ex);
            }

        }
          if (options.isAUTO_SAVE()|| closeWhenReady) {
                ep.removeEvolutionLister(this);
              this.setVisible(false);
              this.dispose();
          }

    }
    public TreePanel getTreePanel(){
        return lastPanel;
    }

    public void simplificationStarted(Simplyfier source) {
        showSimplificationTab();
        jpgbGeneration.setForeground(Color.BLUE);
        jpgbProgress.setMaximum(options.getSIMPLIFICATION_BATCH() * options.getSIMPLIFICATION_GENERATIONS());
        jpgbProgress.setValue(0);
        jpgbGeneration.setMaximum(options.getSIMPLIFICATION_GENERATIONS());
        jpgbGeneration.setValue(0);

    }

    public void simplificationGenerationTerminated(Simplyfier source) {
        jpgbProgress.setValue(options.getSIMPLIFICATION_GENERATIONS() * (source.getCurrentBatch() - 1) + source.getCurrentGeneration());
        jpgbGeneration.setMaximum(source.getCurrentGeneration());

    }

    public void simplifictionTerminated(Simplyfier source) {
        setStopModeOnButtons();
    }
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jpgbProgress = new javax.swing.JProgressBar();
        jpgbGeneration = new javax.swing.JProgressBar();
        jpnlButtons = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jbtnAlternativeS = new javax.swing.JButton();
        jbtnShowSolutions = new javax.swing.JButton();
        jbtnShowPrediction = new javax.swing.JButton();
        jbtnSave = new javax.swing.JButton();
        jbtnSimplify = new javax.swing.JButton();
        jbtnStop = new javax.swing.JButton();
        jbtnStart = new javax.swing.JButton();
        jTabbedPane = new javax.swing.JTabbedPane();
        jpnlTabOptions = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxaOptions = new javax.swing.JTextArea();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setDoubleBuffered(true);
        setPreferredSize(new java.awt.Dimension(116, 200));
        try {
            setSelected(true);
        } catch (java.beans.PropertyVetoException e1) {
            e1.printStackTrace();
        }
        setVisible(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());
        jPanel1.add(jpgbProgress, java.awt.BorderLayout.PAGE_START);
        jPanel1.add(jpgbGeneration, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jpnlButtons.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jButton1.setText("Test");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jpnlButtons.add(jButton1);

        jbtnAlternativeS.setText("Alternative Solution");
        jbtnAlternativeS.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAlternativeSActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnAlternativeS);

        jbtnShowSolutions.setText("Show Solutions");
        jbtnShowSolutions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnShowSolutionsActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnShowSolutions);

        jbtnShowPrediction.setText("Show Prediction"); // NOI18N
        jbtnShowPrediction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnShowPredictionActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnShowPrediction);

        jbtnSave.setText("Save"); // NOI18N
        jbtnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnSaveActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnSave);

        jbtnSimplify.setText("Simplify"); // NOI18N
        jbtnSimplify.setEnabled(false);
        jbtnSimplify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnSimplifyActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnSimplify);

        jbtnStop.setText("Stop"); // NOI18N
        jbtnStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnStopActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnStop);

        jbtnStart.setText("Start"); // NOI18N
        jbtnStart.setDoubleBuffered(true);
        jbtnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnStartActionPerformed(evt);
            }
        });
        jpnlButtons.add(jbtnStart);

        getContentPane().add(jpnlButtons, java.awt.BorderLayout.PAGE_END);

        jTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPaneStateChanged(evt);
            }
        });

        jpnlTabOptions.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setAutoscrolls(true);
        jScrollPane1.setEnabled(false);

        jtxaOptions.setColumns(20);
        jtxaOptions.setEditable(false);
        jtxaOptions.setRows(5);
        jScrollPane1.setViewportView(jtxaOptions);

        jpnlTabOptions.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jTabbedPane.addTab("Options", jpnlTabOptions);

        getContentPane().add(jTabbedPane, java.awt.BorderLayout.CENTER);

        setBounds(0, 0, 772, 348);
    }// </editor-fold>//GEN-END:initComponents
    private void jbtnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnStopActionPerformed
        ep.stopEvolution();
        setStopModeOnButtons();
    }//GEN-LAST:event_jbtnStopActionPerformed

    private void jbtnSimplifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSimplifyActionPerformed

        setRuningModeOnButtons();
        initSimplificationTab();
        if (jTabbedPane.getSelectedComponent() instanceof TreePanel) {
            GP gp = (GP) ((TreePanel) jTabbedPane.getSelectedComponent()).getGP();
            
            ep.startSimplification(gp);
        }

    }//GEN-LAST:event_jbtnSimplifyActionPerformed

    private void jbtnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnStartActionPerformed
        setRuningModeOnButtons();
        ep.startEvolution();
    }//GEN-LAST:event_jbtnStartActionPerformed

    private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSaveActionPerformed
        if (jTabbedPane.getSelectedComponent() instanceof TreePanel) {
            saveSelectedGPTab();
        } else {
            saveSelectedTextAreaTab();
        }

    }//GEN-LAST:event_jbtnSaveActionPerformed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        updateCurrentTab();
    }//GEN-LAST:event_formComponentResized

    private void jTabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPaneStateChanged
        updateCurrentTab();
    }//GEN-LAST:event_jTabbedPaneStateChanged

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
        ep.removeallEvoltuionListeners();
        ep.stopEvolution();

    }//GEN-LAST:event_formInternalFrameClosed

    private void jbtnShowPredictionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnShowPredictionActionPerformed
        try {
            if (jTabbedPane.getSelectedComponent() instanceof TreePanel) {
                TreePanel tp = (TreePanel) jTabbedPane.getSelectedComponent();
                GraphWindow gw = new GraphWindow(tp.getGP(),ep);//GEN-LAST:event_jbtnShowPredictionActionPerformed
                
                JDesktopPane dp = getDesktopPane();
                this.getDesktopPane().add(gw);
                dp.getDesktopManager().resizeFrame(gw, 0, dp.getHeight()/2, dp.getWidth(), dp.getHeight()/2);
      //          gw.setTitle(options.getDATA_FILE());
            gw.setVisible(true);
                tp.setActionListener(gw);
                gw.setVisible(true);
            }
        } catch (GeneException ex) {
            ErrorManager.getInstance().reportError(ex);
        }
    }

                private void jbtnShowSolutionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnShowSolutionsActionPerformed
                	ArrayList<GP> winners = new ArrayList<GP>(options.getWinners());

                    System.out.println("Winners: " + winners.size());
                    MultipleSolutionsFitness msf = (MultipleSolutionsFitness) winners.get(0).getFitnessFunction();

                  //  winners = null;
                  //  msf.removeDuplicates();
                  //  winners = new ArrayList<GP>(options.getWinners());
                 //   System.out.println("Winners without duplicates: " + winners.size());
                    for (GP gp : winners) {
                        try {
                            //msf.recalculateFitness(gp);
                            //System.out.println("TrainAcc: " + gp.getTrainAcc() + " TestAcc: " + gp.getTestAcc() + " LiknessRatio: " + ((double)gp.getLikness())/gp.calcIFs());
                            //System.out.println(gp.getFormatedTree()+" \n");
                        } catch (Exception ex) {
                           ex.printStackTrace();
                        }


                    }
                    TreeComparator tc = new TreeComparator(winners,msf.getJ48GP());
                  //  System.out.println(tc.toString());
                    System.out.println("Likness:\n" + tc.statsToString());
                    System.out.println(tc.gpVsGroupStructure());
                    System.out.println("");
                    System.out.println("");
                    System.out.println(tc.gpVsGroupPrediction());
                    System.out.println("");
                    System.out.println("");
                    System.out.println(tc.gpVsGroupStructurePrediction());
                }//GEN-LAST:event_jbtnShowSolutionsActionPerformed

                private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
                    ep.stopEvolution();
                }//GEN-LAST:event_formInternalFrameClosing

                private void jbtnAlternativeSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAlternativeSActionPerformed
                    /*setRuningModeOnButtons();
                    initSimplificationTab();
                    if (jTabbedPane.getSelectedComponent() instanceof TreePanel) {
                        GP gp = ((TreePanel) jTabbedPane.getSelectedComponent()).getGP();
                        ep.createAlternativeSolution(gp);
                    }*/


                	ArrayList<GP> winners = new ArrayList<GP>(options.getWinners());

                    System.out.println("Winners: " + winners.size());
                    MultipleSolutionsFitness msf = (MultipleSolutionsFitness) winners.get(0).getFitnessFunction();
                    for (GP gp : winners) {
                        try {
                          //  msf.recalculateFitness(gp);
                        } catch (Exception ex) {
                        	ex.printStackTrace();
                        }


                    }
                    TreeComparator tc = new TreeComparator(winners,msf.getJ48GP());
                    System.out.println("Structures Groups--------------------------------------------------------------------------");
                    System.out.println(tc.toString());
                }//GEN-LAST:event_jbtnAlternativeSActionPerformed

                private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
                    System.out.println("No implmentation!");
                    /* try {
                    GrexM5P m5p = new GrexM5P(ep.getData());
                   // ep.getData().initFold("F1");
                    m5p.initFold("F1");
                    m5p.train();    
                    ErrorCalculator ec = new ErrorCalculator(options.getPROBLEM_TYPE());
                    
                        System.out.println(ec.getHeaders()+ec.getStatisitcs(m5p));
                        System.out.println("Size:" + m5p.getNrOfNodes());
                        System.out.println("\n" + m5p);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }*/

                }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JButton jbtnAlternativeS;
    private javax.swing.JButton jbtnSave;
    private javax.swing.JButton jbtnShowPrediction;
    private javax.swing.JButton jbtnShowSolutions;
    private javax.swing.JButton jbtnSimplify;
    private javax.swing.JButton jbtnStart;
    private javax.swing.JButton jbtnStop;
    private javax.swing.JProgressBar jpgbGeneration;
    private javax.swing.JProgressBar jpgbProgress;
    private javax.swing.JPanel jpnlButtons;
    private javax.swing.JPanel jpnlTabOptions;
    private javax.swing.JTextArea jtxaOptions;
    // End of variables declaration//GEN-END:variables
}
